/**
 * 
 */
package com.csu.common.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.csu.common.constants.CommonParams;
import com.csu.cphone.vo.ResultVo;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;

/**
 * @项目名称：cloud_market
 * @类名称：WebUtils
 * @类描述：通用Web工具类
 * @创建人：TangC
 * @创建时间：2015-6-18 下午3:28:11
 */
public class WebUtils
{
    private static Logger LOGGER = Logger.getLogger(WebUtils.class);

    private static String CONTENT_TYPE_JSON = "application/json";

    private static String CONTENT_TYPE_TEXT = "text/plain";

    private WebUtils()
    {

    }

    /**
     * @description：
     * @author dongg
     * @date 2014-6-18
     * @param request
     * @return
     */
    public static Map<String, Object> getParamsMap(HttpServletRequest request)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<?, ?> paramMap = request.getParameterMap();
        for (Map.Entry<?, ?> entry : paramMap.entrySet())
        {
            String key = (String) entry.getKey();
            Object valueObj = entry.getValue();

            if (valueObj == null)
            {
                continue;
            }
            else if (valueObj instanceof String)
            {
                String value = (String) valueObj;
                map.put(key, value);
                LOGGER.debug("====》 parameter：" + key + " : " + value);
            }
            else if (valueObj instanceof String[])
            {
                String[] values = (String[]) valueObj;
                if (values.length == 1)
                {
                    map.put(key, values[0]);
                    LOGGER.debug("====》 parameter：" + key + " : " + values[0]);
                }
                else
                {
                    map.put(key, values);
                    LOGGER.debug("====》 parameter：" + key + " : " + values);
                }
            }
            else
            {
                String value = valueObj.toString();
                map.put(key, value);
                LOGGER.debug("====》 parameter：" + key + " : " + value);
            }

        }
        return map;
    }

    /**
     * @description：返回JSON数据到客户端
     * @param response
     * @param obj
     * @throws JsonGenerationException
     * @throws JsonMappingException
     * @throws IOException
     */
    public static void returnJson(HttpServletResponse response, Object obj)
    {
        WebUtils.printStr2Client(response, JsonUtils.obj2JsonStr(obj), CONTENT_TYPE_JSON);
    }

    /**
     * @description：返回TEXT数据到客户端（上传文件返回字符串 需设置response为text/plain）
     * @param response
     * @param obj
     * @throws JsonGenerationException
     * @throws JsonMappingException
     * @throws IOException
     */
    public static void returnText(HttpServletResponse response, Object obj)
    {
        WebUtils.printStr2Client(response, JsonUtils.obj2JsonStr(obj), CONTENT_TYPE_TEXT);
    }

    /**
     * @description：将字符串输出到客户端(gzip压缩)
     * @param response
     * @param resultStr
     *            要发送的字符串
     * @throws IOException
     */
    private static void printStr2Client(HttpServletResponse response, String resultStr, String contentType)
    {
        response.setCharacterEncoding("utf-8");

        response.setContentType(contentType);

        try
        {
            PrintWriter out = response.getWriter();

            out.println(resultStr);

            out.flush();

            out.close();
        }
        catch (Exception e)
        {
            LOGGER.error("向客户端返回字符串流是发生异常", e);
        }
    }

    /**
     * @description：获取客户端真实IP
     * @author dongg
     * @date 2014-6-12
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request)
    {

        if (request == null)
        {
            return "";
        }
        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1)
        {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        return ip;
    }

    /**
     * @description
     * @author TangC
     * @date 2015-8-23 下午8:31:59
     * @param callback
     * @param json
     * @param request
     *            TODO
     * @return
     */
    public static String returnJsonP(String callback, String json, HttpServletRequest request)
    {
        if (CommonParams.IS_SUPPORT_JSONP && !StringUtils.isEmpty(callback))
        {
            return jsonpResult(callback, json, request);
        }
        return json;
    }

    /**
     * @description
     * @author TangC
     * @date 2015-8-30 下午4:39:32
     * @param callback
     * @param json
     * @param request
     * @return
     */

    private static String jsonpResult(String callback, String json, HttpServletRequest request)
    {
        if ("true".equals(request.getParameter("f")))
        {
            return "<script>parent." + callback + "(" + json + ")</script>";
        }
        return callback + "(" + json + ")";
    }

    /**
     * @description
     * @author TangC
     * @date 2015-8-25 下午5:19:45
     * @param request
     *            TODO
     * @return
     */
    public static String returnSuccessJsonP(String callback, HttpServletRequest request)
    {
        String json = JsonUtils.obj2JsonStr(new ResultVo<Object>());
        if (CommonParams.IS_SUPPORT_JSONP && !StringUtils.isEmpty(callback))
        {
            return jsonpResult(callback, json, request);
        }
        return json;
    }

    /**
     * @description 获取时间的日期戳；如20140906
     * @author TangC
     * @date 2014-9-23 下午3:47:22
     * @param date
     * @return
     */
    public static String getDayString(Date date, String formatString)
    {
        // 获取时间字符串
        String currentDateSTring = convertDate2String(date, formatString);
        // 获取当前时间的日期戳
        String currentDayString = currentDateSTring.substring(0, 8);

        return currentDayString;
    }

    /**
     * @description
     * @author TangC
     * @date 2014-9-23 下午2:56:34
     * @param date
     * @param formatString
     * @return
     */
    public static String convertDate2String(Date date, String formatString)
    {
        SimpleDateFormat format = new SimpleDateFormat(formatString);
        return format.format(date);
    }

}
